'use client';

import { useState, useEffect } from 'react';
import { ArrowUp, ChevronUp, Rocket, Zap } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

interface BackToTopProps {
  className?: string;
  variant?: 'default' | 'circular' | 'minimal' | 'animated';
  position?: 'bottom-right' | 'bottom-left' | 'bottom-center';
  showAfter?: number;
  smooth?: boolean;
  icon?: 'arrow' | 'chevron' | 'rocket' | 'zap';
  size?: 'sm' | 'md' | 'lg';
}

/**
 * 返回顶部按钮组件
 * 支持多种样式和动画效果
 */
export function BackToTop({
  className,
  variant = 'default',
  position = 'bottom-right',
  showAfter = 300,
  smooth = true,
  icon = 'arrow',
  size = 'md',
}: BackToTopProps) {
  const [isVisible, setIsVisible] = useState(false);
  const [scrollProgress, setScrollProgress] = useState(0);

  useEffect(() => {
    /**
     * 处理滚动事件
     */
    const handleScroll = () => {
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      const scrollHeight =
        document.documentElement.scrollHeight - window.innerHeight;
      const progress = scrollHeight > 0 ? (scrollTop / scrollHeight) * 100 : 0;

      setScrollProgress(Math.min(100, Math.max(0, progress)));
      setIsVisible(scrollTop > showAfter);
    };

    // 节流处理
    let ticking = false;
    const throttledHandleScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          handleScroll();
          ticking = false;
        });
        ticking = true;
      }
    };

    window.addEventListener('scroll', throttledHandleScroll, { passive: true });
    handleScroll(); // 初始检查

    return () => {
      window.removeEventListener('scroll', throttledHandleScroll);
    };
  }, [showAfter]);

  /**
   * 滚动到顶部
   */
  const scrollToTop = () => {
    if (smooth) {
      window.scrollTo({
        top: 0,
        behavior: 'smooth',
      });
    } else {
      window.scrollTo(0, 0);
    }
  };

  /**
   * 获取图标组件
   */
  const getIcon = () => {
    const iconProps = {
      className: cn(
        size === 'sm' && 'w-4 h-4',
        size === 'md' && 'w-5 h-5',
        size === 'lg' && 'w-6 h-6'
      ),
    };

    switch (icon) {
      case 'chevron':
        return <ChevronUp {...iconProps} />;
      case 'rocket':
        return <Rocket {...iconProps} />;
      case 'zap':
        return <Zap {...iconProps} />;
      default:
        return <ArrowUp {...iconProps} />;
    }
  };

  /**
   * 获取位置样式
   */
  const getPositionClasses = () => {
    switch (position) {
      case 'bottom-left':
        return 'bottom-8 left-8';
      case 'bottom-center':
        return 'bottom-8 left-1/2 -translate-x-1/2';
      default:
        return 'bottom-8 right-8';
    }
  };

  /**
   * 获取尺寸样式
   */
  const getSizeClasses = () => {
    switch (size) {
      case 'sm':
        return 'w-10 h-10';
      case 'lg':
        return 'w-14 h-14';
      default:
        return 'w-12 h-12';
    }
  };

  if (!isVisible) return null;

  // 默认样式
  if (variant === 'default') {
    return (
      <Button
        onClick={scrollToTop}
        className={cn(
          'fixed z-50 transition-all duration-300 shadow-lg hover:shadow-xl',
          'bg-primary hover:bg-primary/90 text-primary-foreground',
          'rounded-full p-0',
          getSizeClasses(),
          getPositionClasses(),
          'hover:scale-110 active:scale-95',
          className
        )}
        title="返回顶部"
      >
        {getIcon()}
      </Button>
    );
  }

  // 圆形进度样式
  if (variant === 'circular') {
    const radius = size === 'sm' ? 18 : size === 'lg' ? 26 : 22;
    const circumference = radius * 2 * Math.PI;
    const strokeDasharray = circumference;
    const strokeDashoffset =
      circumference - (scrollProgress / 100) * circumference;

    return (
      <div
        className={cn(
          'fixed z-50 transition-all duration-300 cursor-pointer group',
          getPositionClasses(),
          className
        )}
        onClick={scrollToTop}
        title="返回顶部"
      >
        <div className="relative">
          {/* 背景圆圈 */}
          <div
            className={cn(
              'rounded-full bg-white dark:bg-gray-900 shadow-lg border border-gray-200 dark:border-gray-700',
              'group-hover:shadow-xl transition-shadow duration-300',
              getSizeClasses()
            )}
          >
            <svg
              className={cn(
                'w-full h-full transform -rotate-90',
                getSizeClasses()
              )}
              viewBox={`0 0 ${(radius + 4) * 2} ${(radius + 4) * 2}`}
            >
              {/* 背景圆圈 */}
              <circle
                cx={radius + 4}
                cy={radius + 4}
                r={radius}
                stroke="currentColor"
                strokeWidth={2}
                fill="none"
                className="text-gray-200 dark:text-gray-700"
              />

              {/* 进度圆圈 */}
              <circle
                cx={radius + 4}
                cy={radius + 4}
                r={radius}
                stroke="#3b82f6"
                strokeWidth={2}
                fill="none"
                strokeLinecap="round"
                strokeDasharray={strokeDasharray}
                strokeDashoffset={strokeDashoffset}
                className="transition-all duration-150 ease-out"
              />
            </svg>
          </div>

          {/* 图标 */}
          <div className="absolute inset-0 flex items-center justify-center text-gray-600 dark:text-gray-300 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
            {getIcon()}
          </div>
        </div>
      </div>
    );
  }

  // 最小化样式
  if (variant === 'minimal') {
    return (
      <button
        onClick={scrollToTop}
        className={cn(
          'fixed z-50 transition-all duration-300',
          'bg-gray-100 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700',
          'text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100',
          'rounded-lg p-2 shadow-sm hover:shadow-md',
          'opacity-70 hover:opacity-100',
          getPositionClasses(),
          className
        )}
        title="返回顶部"
      >
        {getIcon()}
      </button>
    );
  }

  // 动画样式
  if (variant === 'animated') {
    return (
      <div
        className={cn(
          'fixed z-50 transition-all duration-300 cursor-pointer group',
          getPositionClasses(),
          className
        )}
        onClick={scrollToTop}
        title="返回顶部"
      >
        <div
          className={cn(
            'relative rounded-full bg-gradient-to-r from-blue-500 to-purple-600 shadow-lg',
            'group-hover:shadow-xl group-hover:scale-110 transition-all duration-300',
            'text-white',
            getSizeClasses()
          )}
        >
          {/* 脉冲动画 */}
          <div
            className={cn(
              'absolute inset-0 rounded-full bg-gradient-to-r from-blue-500 to-purple-600',
              'animate-ping opacity-20',
              getSizeClasses()
            )}
          />

          {/* 图标 */}
          <div className="relative flex items-center justify-center w-full h-full group-hover:animate-bounce">
            {getIcon()}
          </div>
        </div>
      </div>
    );
  }

  return null;
}

/**
 * 浮动返回顶部按钮
 * 带有更丰富的交互效果
 */
export function FloatingBackToTop({
  className,
  showAfter = 400,
}: {
  className?: string;
  showAfter?: number;
}) {
  const [isVisible, setIsVisible] = useState(false);
  const [isHovered, setIsHovered] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      setIsVisible(scrollTop > showAfter);
    };

    let ticking = false;
    const throttledHandleScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          handleScroll();
          ticking = false;
        });
        ticking = true;
      }
    };

    window.addEventListener('scroll', throttledHandleScroll, { passive: true });
    handleScroll();

    return () => {
      window.removeEventListener('scroll', throttledHandleScroll);
    };
  }, [showAfter]);

  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };

  return (
    <div
      className={cn(
        'fixed bottom-8 right-8 z-50 transition-all duration-500',
        isVisible
          ? 'opacity-100 translate-y-0'
          : 'opacity-0 translate-y-16 pointer-events-none',
        className
      )}
    >
      <div
        className="relative group cursor-pointer"
        onClick={scrollToTop}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      >
        {/* 主按钮 */}
        <div
          className={cn(
            'w-14 h-14 rounded-full bg-white dark:bg-gray-900 shadow-lg border border-gray-200 dark:border-gray-700',
            'flex items-center justify-center transition-all duration-300',
            'group-hover:shadow-xl group-hover:scale-110 group-hover:bg-blue-50 dark:group-hover:bg-blue-950'
          )}
        >
          <ArrowUp
            className={cn(
              'w-6 h-6 text-gray-600 dark:text-gray-400 transition-all duration-300',
              'group-hover:text-blue-600 dark:group-hover:text-blue-400',
              isHovered && 'animate-bounce'
            )}
          />
        </div>

        {/* 提示文本 */}
        <div
          className={cn(
            'absolute right-16 top-1/2 -translate-y-1/2 transition-all duration-300',
            'bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900',
            'px-3 py-1 rounded-lg text-sm whitespace-nowrap shadow-lg',
            isHovered
              ? 'opacity-100 translate-x-0'
              : 'opacity-0 translate-x-2 pointer-events-none'
          )}
        >
          返回顶部
          <div className="absolute left-full top-1/2 -translate-y-1/2 border-4 border-transparent border-l-gray-900 dark:border-l-gray-100" />
        </div>

        {/* 装饰性光环 */}
        <div
          className={cn(
            'absolute inset-0 rounded-full bg-blue-400 opacity-0 transition-opacity duration-300',
            'animate-ping',
            isHovered && 'opacity-20'
          )}
        />
      </div>
    </div>
  );
}

/**
 * 侧边返回顶部按钮
 * 固定在页面侧边的返回顶部功能
 */
export function SideBackToTop({
  className,
  side = 'right',
}: {
  className?: string;
  side?: 'left' | 'right';
}) {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      setIsVisible(scrollTop > 200);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    handleScroll();

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };

  return (
    <div
      className={cn(
        'fixed top-1/2 -translate-y-1/2 z-40 transition-all duration-300',
        side === 'left' ? 'left-4' : 'right-4',
        isVisible
          ? 'opacity-100 translate-x-0'
          : side === 'left'
            ? 'opacity-0 -translate-x-full'
            : 'opacity-0 translate-x-full',
        className
      )}
    >
      <button
        onClick={scrollToTop}
        className={cn(
          'w-10 h-16 bg-white dark:bg-gray-900 shadow-lg border border-gray-200 dark:border-gray-700',
          'flex items-center justify-center transition-all duration-300',
          'hover:shadow-xl hover:bg-blue-50 dark:hover:bg-blue-950',
          side === 'left' ? 'rounded-r-full' : 'rounded-l-full'
        )}
        title="返回顶部"
      >
        <ArrowUp className="w-5 h-5 text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors" />
      </button>
    </div>
  );
}
